package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.file.MinIOTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {

    @Resource
    private Configuration configuration;

    @Resource
    private MinIOTemplate minIOTemplate;

    @Override
    public String buildArticle2Minio(Long id, String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        try {
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("content", JSON.parseArray(content));
            //2.2 加载模板
            Template template = configuration.getTemplate("article.ftl");
            //2.3 生成页面
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);

            //3. 将静态HTML页面上传到minio
            ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOTemplate.uploadHtmlFile("", id + ".html", is);
            System.out.println(url);

            return url;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }

    }
}
